﻿#include "requestmapper.h"
#include "global.h"
#include "controller/logincontroller.h"
#include "controller/funcvercodecontroller.h"
#include "controller/sysmsgcontroller.h"
#include "controller/sysusercontroller.h"
#include "controller/commoncontroller.h"
#include "controller/sysmenucontroller.h"
#include "controller/sysdiccontroller.h"
#include "controller/sysrolecontroller.h"
#include "controller/sysdeptcontroller.h"
#include "controller/syslogcontroller.h"
#include "controller/funcmonitorcontroller.h"
#include "controller/sysusermsgcontroller.h"
#include "controller/funcsmscontroller.h"
#include "controller/funcemailcontroller.h"
#include "controller/funcloadcontroller.h"
#include "controller/funcexportcontroller.h"

RequestMapper::RequestMapper(QObject* parent)
    :HttpRequestHandler(parent)
{
    qDebug("RequestMapper: created");
}


RequestMapper::~RequestMapper()
{
    qDebug("RequestMapper: deleted");
}


void RequestMapper::service(HttpRequest& request, HttpResponse& response)
{
    QByteArray path = request.getPath().toLower();
    QString tmp = QString(path);
    qDebug("RequestMapper::service e");

    //实现跨域访问，js 调用API 提供了支持。
    response.setHeader("Connection", "keep-alive");
    auto origin = request.getHeader("Origin");
    response.setHeader("Access-Control-Allow-Origin", origin);
    response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
    response.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,x-token,access_token");
    response.setHeader("Access-Control-Max-Age", "86400");
    response.setHeader("Vary", "Accept-Encoding,Origin");
    response.setHeader("Keep-Alive", "timeout=2,max=99");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    //set api header
    response.setHeader("Content-Type", "application/json; charset=utf-8");
    //response.setHeader("Access-Control-Allow-Origin", "*"); // also important , if not set , the html application wont run.
    if (request.getMethod() == "OPTIONS")
    {
        response.setStatus(200,"OK");
        qDebug("RequestMapper: finished request");
        // Clear the log buffer

        return;
    }

    //拦截部分，做token校验
    if (path.startsWith("/func")
            || path.startsWith("/sys")
            || path.startsWith("/monitor/"))
    {
        if(!preHandle(request, response))
            return;
    }

    if (path.startsWith("/login") || path.startsWith("/logout"))
    {
        LoginController().service(request, response);
    }
    else if (path.startsWith("/vercode"))
    {
        FuncVercodeController().service(request, response);
    }
    else if (path.startsWith("/func/message/user/"))
    {
        SysUserMsgController().service(request, response);
    }
    else if (path.startsWith("/func/message/sys/"))
    {
        SysMsgController().service(request, response);
    }
    else if (path.startsWith("/sys/user/"))
    {
        SysUserController().service(request, response);
    }
    else if (path.startsWith("/sys/menu/"))
    {
        SysMenuController().service(request, response);
    }
    else if (path.startsWith("/sys/dic/"))
    {
        SysDicController().service(request, response);
    }
    else if (path.startsWith("/sys/role/"))
    {
        SysRoleController().service(request, response);
    }
    else if (path.startsWith("/sys/dept/"))
    {
        SysDeptController().service(request, response);
    }
    else if (path.startsWith("/sys/log/"))
    {
        SysLogController().service(request, response);
    }
    else if (path.startsWith("/func/sms/"))
    {
        FuncSmsController().service(request, response);
    }
    else if (path.startsWith("/sys/email/"))
    {
        FuncEmailController().service(request, response);
    }
    else if (path.startsWith("/func/upload/"))
    {
        FuncLoadController().service(request, response);
    }
    else if (path.startsWith("/func/export/"))
    {
        FuncExportController().service(request, response);
    }
    else if (path.startsWith("/monitor"))
    {
        FuncMonitorController().service(request, response);
    }
    else if (path.startsWith("/common"))
    {
        CommonController().service(request, response);
    }
    else
    {
        staticFileController->service(request, response);
    }


    qDebug("RequestMapper: finished request");

    // Clear the log buffer
    if (logger)
    {
    //   logger->clear();
    }
}

// 拦截未授权操作
bool RequestMapper::preHandle(HttpRequest& request, HttpResponse& response)
{
    // token校验不通过，返回1001
    ResultJson result(1001, false, QStringLiteral("token已失效"));
    QString accessToken = request.getHeader("access_token");
    if(accessToken == NULL || accessToken.isEmpty())
        accessToken = request.getParameter("access_token");

    if(accessToken == NULL || accessToken.isEmpty())
    {
        result.failedMsg(QStringLiteral("找不到token"));
        ResponseUtil::replyJson(response, result);
        //staticFileController->service(request, response);
        return false;
    }

    //根据token登录
    QString username = JwtUtil::getUsername(accessToken);
    if(username == NULL || username.isEmpty())
    {
        ResponseUtil::replyJson(response, result);
        //staticFileController->service(request, response);
        return false;
    }

    //判断token是否有效
    QString token_key = username + "_token";
    QString saveToken = CacheApi::instance()->get(token_key);
    if(saveToken != accessToken)
    {
        ResponseUtil::replyJson(response, result);
        //staticFileController->service(request, response);
        return false;
    }

    //刷新token
    CacheApi::instance()->insert(token_key, accessToken, JwtUtil::EXPIRED_TIME);

    return true;
}
